package com.example.elasticsearch.studynote;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.util.Map;

public class ElasticsearchSearchExample {

    public static void main(String[] args) {
        // 创建Elasticsearch客户端
        try (RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")))) {

            // 创建搜索请求
            SearchRequest searchRequest = new SearchRequest("your-index-name");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            // 定义查询条件，这里是一个简单的匹配查询
            searchSourceBuilder.query(QueryBuilders.matchQuery("field_name", "search_term"));

            // 设置高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            HighlightBuilder.Field highlightField = new HighlightBuilder.Field("field_name");
            highlightField.highlighterType("unified"); // 选择高亮类型
            highlightBuilder.field(highlightField);
            searchSourceBuilder.highlighter(highlightBuilder);

            searchRequest.source(searchSourceBuilder);

            // 执行搜索
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            // 处理搜索结果，包含高亮部分
            for (SearchHit hit : searchResponse.getHits().getHits()) {
                System.out.println("Document: " + hit.getSourceAsString());

                // 获取高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField highlight = highlightFields.get("field_name");
                if (highlight != null) {
                    Text[] fragments = highlight.fragments();
                    StringBuilder highlightedText = new StringBuilder();
                    for (Text fragment : fragments) {
                        highlightedText.append(fragment.string());
                    }
                    System.out.println("Highlighted: " + highlightedText.toString());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
